今天來做個簡單的東西,會使用TimePickerDialog,利用TextView顯示出時間。
activity_main.xml設置
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/puttime"
android:layout_alignParentEnd="true"
android:layout_marginEnd="160dp"
android:layout_marginBottom="10dp"
android:text="設置時間"
android:textSize="40sp" />
<EditText
android:id="@+id/puttime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"
android:layout_marginBottom="100dp"
android:ems="10"
android:hint="Enter Time" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginLeft="100dp"
android:layout_marginEnd="160dp"
android:layout_marginBottom="300dp"
android:text="click" />
</RelativeLayout>
MainActivity程式設計
public class MainActivity extends AppCompatActivity {
//宣告物件
private TextView time;
private Button button;
private EditText puttime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//點擊監聽EditText
puttime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar calendar=Calendar.getInstance();
int hour=calendar.get(Calendar.HOUR_OF_DAY);
int min=calendar.get(Calendar.MINUTE);
//新增TimePickerDialog,設定點擊監聽
TimePickerDialog timePickerDialog= new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int min) {
//EditText顯示時間
puttime.setText(hour+":"+min);
}
}
, hour,min,true);
//記得show出來喔
timePickerDialog.show();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//TextView顯示puttime獲取的文字
time.setText(puttime.getText());
}
});
}
private void init() {
time = (TextView) findViewById(R.id.time);
puttime = (EditText) findViewById(R.id.puttime);
button = (Button) findViewById(R.id.button);
}
}
成果圖